package com.woniuxy.service.Impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.demo.Result;
import com.woniuxy.exception.PawnJurisdictionException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录失败
 */
public class LoginErrorHandler implements AuthenticationFailureHandler {

    private ObjectMapper om = new ObjectMapper();

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
            throws IOException, ServletException {
        response.setCharacterEncoding("utf8");
        response.setContentType("application/json;charset=utf8");


        int code = 500;
        if (exception instanceof PawnJurisdictionException) {
            code = 403;
        }

        Result result = Result.newInstance()
                .setCode(code).setMsg(exception.getMessage()).setData(exception.getMessage());

        String json = om.writeValueAsString(result);
        response.getWriter().write(json);
        response.getWriter().flush();
    }

}